#include "AsioIoContextPool.h"
#include "log.h"

AsioIoContextPool::AsioIoContextPool(std::size_t size)
:_io_contexts(size)
,_works(size)
,_next(0)
{
    for (std::size_t i = 0; i < size; ++i)
    {
        _works[i] = std::make_shared<Work>(_io_contexts[i]);
        _threads.emplace_back([this, i]()
        {
            _io_contexts[i].run();
        });
    }
}


AsioIoContextPool::IOContext& AsioIoContextPool::GetIoContext()
{
    size_t index = _next++ % _io_contexts.size();
    return _io_contexts[index];
}


void AsioIoContextPool::Stop()
{
    for(auto& work : _works)
    {
        work->get_io_context().stop();
        work.reset();
    }

    for (auto& thread : _threads)
    {
        if (thread.joinable())
        {
            thread.join();
        }
    }
    log_info("AsioIoContextPool stopped.");
}